const xlsx = require('node-xlsx')

function findCompanyDataByFilter(filterOb = {}, $db) {
  return new Promise((resolve) => {
    $db.companyData.find(filterOb).sort({ code: 1 }).exec((err, docs) => {
      resolve({
        data: docs,
        err
      })
    })
  })
}

function findGoodDataByFilter(filterOb = {}, $db) {
  return new Promise((resolve) => {
    $db.goodsData.find(filterOb).exec((err, docs) => {
      resolve({
        data: docs,
        err
      })
    })
  })
}

function difference(arra, arrb) {
  return Array.from(new Set([...arra].filter(x => !arrb.includes(x))))
}

async function getGoodModel(value, goodsModel, $db) {
  const searchArr = []
  searchArr.push({
    goodsHsCode: new RegExp(value)
  })
  const res = await findCompanyDataByFilter({ $and: searchArr }, $db)
  let dest = goodsModel
  const _data = res.data
  const len = _data.length
  if (len) {
    const compareOptions = goodsModel.split('|')
    for (var i = 0; i < len; i++) {
      const _itemOptions = [..._data[i].goodsModel.split('|')]
      _itemOptions.splice(0, 2)
      if (!difference(compareOptions, _itemOptions).length && !difference(_itemOptions, compareOptions).length) {
        dest = _data[i].goodsModel
        break
      }
    }
  }
  return dest
}

function getResetUnit(value, list) {
  const curItem = list.find(item => (item.code === value || item.name === value)) || {}
  return {
    currency: curItem.code,
    currencyName: curItem.name
  }
}

function getResetUnit2(value, list) {
  const curItem = list.find(item => (item.code === value || item.name === value)) || {}
  return {
    quantityUnit: curItem.code,
    quantityUnitName: curItem.name
  }
}

function getResetUnit3(value, list) {
  const curItem = list.find(item => (item.code === value || item.name === value)) || {}
  return {
    dutyMode: curItem.code,
    dutyModeName: curItem.name
  }
}

async function getFaxNumber(value, number, $db) {
  const searchArr = []
  searchArr.push({
    hsCode: new RegExp(value)
  })
  const res = await findGoodDataByFilter({ $and: searchArr }, $db)
  const {
    firstUnit,
    firstUnitName,
    secondUnitName,
    secondUnit
  } = res.data[0]
  const obj = {
    firstUnit,
    firstUnitName,
    secondUnitName,
    secondUnit
  }
  if (firstUnit === '035') {
    obj.firstQuantity = number
  } else if (secondUnit === '035') {
    obj.secondQuantity = number
  }
  return obj
}

function parseFile(filename, $db, bilists, unitlists, mainslists) {
  const obj = xlsx.parse(filename)
  const arr = obj[0].data
  if (arr.length > 1) {
    return Promise.all(arr.map(async(item, index) => {
      if (index > 0) {
        const [goodsNo, goodsHsCode, goodsCnName, goodsModel, totalWeight, quantity, quantityUnit, unitPrice, totalPrice, currency, v1, v2, v3, v4, dutyMode] = item
        console.log(v1, v2, v3, v4)
        const obj = {
          goodsNo, goodsHsCode, goodsCnName, dutyMode, totalPrice, quantity,
          unitPrice: parseFloat(totalPrice / quantity).toFixed(4) || unitPrice,
          goodsModel: await getGoodModel(goodsHsCode, goodsModel, $db),
          ...await getFaxNumber(goodsHsCode, totalWeight, $db),
          ...getResetUnit(currency, bilists),
          ...getResetUnit2(quantityUnit, unitlists),
          ...getResetUnit3(dutyMode + '', mainslists)
        }
        return obj
      }
    }))
  } else {
    return []
  }
}

export {
  parseFile
}
